package com.ruoyi.combat.config;


import com.ruoyi.combat.domain.apprisk.CombatPhone;
import com.ruoyi.combat.mapper.apprisk.CombatPhoneMapper;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;

@Component
public class PhoneLoginStateTask {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private CombatPhoneMapper combatPhoneMapper;

    @Scheduled(fixedRate = 30000)
    public void execute() {
        Collection<String> keys = redisCache.keys(Constants.LOGIN_PHONE_KEY + "*");
        if(keys!=null) {
            for (String key : keys) {
                Map cacheObject = redisCache.getCacheObject(key);
                Long date = (Long) cacheObject.get("date");
                String token = (String) cacheObject.get("token");
                String phoneNum = (String) cacheObject.get("phoneNum");
                if (System.currentTimeMillis() - date > 90000) {
                    CombatPhone combatPhone = combatPhoneMapper.selectCombatPhoneByPhoneNum(phoneNum);
                    if(combatPhone!=null){
                        combatPhone.setPhoneState("离线");
                        combatPhoneMapper.updateCombatPhone(combatPhone);
                    }
                    redisCache.deleteObject(key);
                    tokenService.delLoginUser(token);
                }
            }
        }
    }


}
